package com.api.client.imp;

import org.scribe.builder.api.Api;
import org.scribe.builder.api.DefaultApi10a;
import org.scribe.model.OAuthConfig;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;

import com.api.client.AccessKeys;
import com.api.client.ApiConfig;
import com.api.client.ApiProvider;

public class OAuthProvider implements ApiProvider{

	private final ApiConfig config;
	
	private final OAuthService service;
	
	public OAuthProvider(ApiConfig config, String consumerKey, String consumerSecret){
		
		this.config = config;
		
		Api api = getOAuthApi(config);
		this.service = api.createService(new OAuthConfig(consumerKey, consumerSecret));
	}
	
	public AccessKeys getAccessKeys(String email, String password) {
		
		Token requestToken = service.getRequestToken();
		
		OAuthRequest oAuthRequest = new OAuthRequest(Verb.POST, config.getAuthorizationUrl());
		
		oAuthRequest.addBodyParameter("request_token", requestToken.getToken());
		oAuthRequest.addBodyParameter("username", email);
		oAuthRequest.addBodyParameter("password", password);
		
		oAuthRequest.send();
		
		Token accessToken = service.getAccessToken(requestToken, new Verifier(""));
		
		return new AccessKeys(accessToken.getToken(), accessToken.getSecret());
	}
	
	private Api getOAuthApi(final ApiConfig config){
		
		return new DefaultApi10a(){
			@Override
			public String getRequestTokenEndpoint() {
				return config.getRequestEndpoint();
			}
			@Override
			public String getAccessTokenEndpoint() {
				return config.getAccessEndpoint();
			}
			@Override
			public String getAuthorizationUrl(Token requestToken) {
				return null;
			}};
	}
}
